package com.element.controller;

import com.element.entity.User;
import com.element.service.UserService;
import com.element.vo.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 查找所有用户信息
    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    // 更新用户信息
    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        Result result = new Result();
        System.out.println(user);
        try {
            userService.update(user);
            result.setMsg("更新用户信息成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("系统错误：更新用户信息失败！");
        }
        return result;
    }

    // 保存用户信息
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        Result result = new Result();
        try {
            userService.save(user);
            result.setMsg("保存用户信息成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("系统错误：保存用户信息失败！");
        }
        return result;
    }


    // 删除用户信息
    @PostMapping("/delete")
    public Result delete(String id) {
        Result result = new Result();
        try {
            userService.delete(id);
            result.setMsg("删除用户成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("系统错误：删除用户信息失败！");
        }
        return result;
    }

    @GetMapping("/findByPage")
    public Map<String,Object> findByPage(Integer currentPage, Integer pageSize) {
        currentPage = currentPage == null ? 0 : currentPage;
        pageSize = pageSize == null ? 14 : pageSize;
        Map<String, Object> map = new HashMap(1024);
        map.put("user", userService.findByPage(currentPage, pageSize));
        map.put("pageTotal", userService.findTotal());
        return map;
    }
}
